package commons;

import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * aipface
 * User: 邱
 * Date: 2024/12/21 11:31
 * Description:
 * Version: V1.0
 */
public class BaiduAIUtil {
    //设置APPID/AK/SK
    public static final String APP_ID = "116760830";
    public static final String API_KEY = "YczzvKeoR3Jmiln7pfmWafho";
    public static final String SECRET_KEY = "WcSm6D10BsVXBXs6YUhWjm4yUytf7dyR";
    public static final String imageType = "BASE64";
    public static final String groupId = "yun_1";
    private AipFace client;
    private HashMap options = new HashMap<String, Object>();
    public BaiduAIUtil() {
        options.put("quality_control","NORMAL");//图片质量
        options.put("liveness_control","LOW");//活体检测
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    }

    /**
     * 人脸注册
     * @param image 图片base64格式
     * @param userInfo 用户信息
     * @param userId 用户ID
     */
    public Boolean addUser(String image, String userInfo, String userId) {
        options.put("user_info", userInfo);
        options.put("action_type", "REPLACE");

        // 人脸注册
        JSONObject res = client.addUser(image, imageType, groupId, userId, options);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0 ? true : false;
    }

    /**
     * 人脸搜索
     * @param image 图片base64格式
     */
    public String search(String image) {
        // 人脸搜索
        JSONObject res = client.search(image, imageType, groupId, options);
        //判断是否在人脸库中
        if (res.has("error_code") && res.getInt("error_code") == 0){
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
            if (userList.length() > 0){
                //获取第一个人脸信息
                JSONObject user = userList.getJSONObject(0);
                double score = user.getDouble("score");
                //分数大于80，返回人脸信息
                if (score > 80){
                    return user.getString("user_info");
                }
            }
        }
        return null;
    }

    /**
     * 人脸检测
     * @param image 图片base64格式
     */
    public Boolean detect(String image) {
        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);
        if (res.has("error_code") && res.getInt("error_code") == 0){
            JSONObject result = res.getJSONObject("result");
            Integer faceNum = result.getInt("face_num");
            return faceNum == 1 ? true : false;
        }
        return false;
    }

    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     *
     * @param imgPath
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小（字节）="+in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }
}
